package com.iap.client.mediator
{
	import com.iap.app.AppGlobal;
	import com.iap.app.StatusCode;
	import com.iap.app.model.ServiceResponse;
	import com.iap.client.view.client.ClientEditWindow;
	import com.iap.common.event.ClientEvent;
	import com.iap.common.event.ClientLiteEvent;
	import com.iap.common.mediator.BaseMediator;
	import com.iap.common.model.Client;
	import com.iap.common.model.ClientLite;
	import com.iap.common.signal.ClientLiteRequestSignal;
	import com.iap.common.signal.ClientRequestSignal;
	
	import mx.events.CloseEvent;
	
	public class ClientEditWindowMediator extends BaseMediator
	{
		[Inject]
		public var view:ClientEditWindow;
		[Inject]
		public var clientRequest:ClientLiteRequestSignal;
		
		override public function onRegister():void
		{
			view.onCancel.add(onCancel);
			view.onSubmit.add(onSubmit);
			addContextListener(ClientLiteEvent.RESPONSE, clientResponseHandler);
		}

		private function onCancel(itemName:String):void
		{
			closeView();
		}
		
		private function closeView():void
		{
			view.dispatchEvent(new CloseEvent(CloseEvent.CLOSE));
			view.closeView();
		}

		private function onSubmit(model:ClientLite, task:String):void
		{
			AppGlobal.startWait();
			clientRequest.dispatch(model, task);
		}

		private function clientResponseHandler(evt:ClientLiteEvent):void
		{
			AppGlobal.endWait();
			var response:ServiceResponse = evt.response;
			if(response.task == ClientLiteRequestSignal.SAVE)
			{
				if(!view.canCloseForm)
					return;
			}
			if(response.status.code == StatusCode.OK || view.canCloseForm)
				closeView();
		}
	}
}